<template>
  <section class="app-main">
    <div class="app-container">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="库位编码">
          <el-input v-model="queryParams.area_code" placeholder="请输入库位编码" />
        </el-form-item>
        <el-form-item label="库位名称">
          <el-input v-model="queryParams.area_name" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="库位位置">
          <el-input-number v-model="queryParams.position_x" placeholder="X" :min="0" controls-position="right" />
          <el-input-number v-model="queryParams.position_y" placeholder="Y" :min="0" controls-position="right" />
          <el-input-number v-model="queryParams.position_z" placeholder="Z" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="mb8 el-row">
        <el-button type="primary" plain @click="handleAdd">
          <i class="el-icon-plus"></i> 新增
        </el-button>
        <el-button type="success" plain :disabled="selectedRows.length !== 1" @click="handleUpdate(selectedRows[0])">
          <i class="el-icon-edit"></i> 修改
        </el-button>
        <el-button type="danger" plain :disabled="!selectedRows.length" @click="handleDelete()">
          <i class="el-icon-delete"></i> 删除
        </el-button>
        <div class="top-right-btn">
          <el-button icon="el-icon-search" circle />
          <el-button icon="el-icon-refresh" circle @click="getList" />
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="库位编码" prop="area_code" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row)">{{ scope.row.area_code }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="库位名称" prop="area_name" align="center" />
        <el-table-column label="面积" prop="area" align="center" />
        <el-table-column label="最大载重量" prop="max_weight" align="center" />
        <el-table-column label="单位名称" prop="units.unit_name" align="center" />
        <el-table-column label="已用容量" align="center">
          <template slot-scope="scope">
            <span :style="getUsageStyle(scope.row)">{{ scope.row.used_capacity + '%' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库位位置X" prop="position_x" align="center" />
        <el-table-column label="库位位置Y" prop="position_y" align="center" />
        <el-table-column label="库位位置Z" prop="position_z" align="center" />
        <el-table-column label="允许产品混放" prop="product_mixing" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.product_mixing === 'Y' ? '' : 'danger'">
              {{ scope.row.product_mixing === 'Y' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="允许批次混放" prop="batch_mixing" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.batch_mixing === 'Y' ? '' : 'danger'">
              {{ scope.row.batch_mixing === 'Y' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" prop="enable_flag" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.enable_flag === 'Y' ? '' : 'danger'">
              {{ scope.row.enable_flag === 'Y' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否冻结" prop="frozen_flag" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.frozen_flag"
              active-value="Y"
              inactive-value="N"
              @change="handleFrozenChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 新增/修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="库位编码" prop="area_code">
            <div style="display: flex; align-items: center;">
              <el-input v-model="form.area_code" placeholder="请输入库位编码" :disabled="form.autoCode" style="width: 300px;" />
              <el-switch v-model="form.autoCode" style="margin-left:10px;" @change="handleAutoCodeChange" />
              <span style="margin-left:5px; white-space:nowrap;">自动生成</span>
            </div>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="库位名称" prop="area_name">
                <el-input v-model="form.area_name" placeholder="请输入库位名称" style="width: 300px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unit_id">
                <el-select v-model="form.unit_id" placeholder="请选择单位">
                  <el-option v-for="item in unitOptions" :key="item.unit_id" :label="item.unit_name" :value="item.unit_id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面积" prop="area">
                <el-input-number v-model="form.area" :min="1" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大载重量" prop="max_weight">
                <el-input-number v-model="form.max_weight" :min="1" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位位置X" prop="position_x">
                <el-input-number v-model="form.position_x" :min="1" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位位置Y" prop="position_y">
                <el-input-number v-model="form.position_y" :min="1" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位位置Z" prop="position_z">
                <el-input-number v-model="form.position_z" :min="1" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="允许产品混放" prop="product_mixing">
                <el-switch
                  v-model="form.product_mixing"
                  active-value="Y"
                  inactive-value="N"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="允许批次混放" prop="batch_mixing">
                <el-switch
                  v-model="form.batch_mixing"
                  active-value="Y"
                  inactive-value="N"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enable_flag">
                <el-switch
                  v-model="form.enable_flag"
                  active-value="Y"
                  inactive-value="N"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否冻结" prop="frozen_flag">
                <el-switch
                  v-model="form.frozen_flag"
                  active-value="Y"
                  inactive-value="N"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="库位详情" :visible.sync="viewDialogVisible" width="800px" append-to-body>
        <el-form label-width="120px" :model="viewForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="库位编码">
                <el-input v-model="viewForm.area_code" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库位名称">
                <el-input v-model="viewForm.area_name" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单位名称">
                <el-input :value="viewForm.units ? viewForm.units.unit_name : ''" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面积(㎡)">
                <el-input v-model="viewForm.area" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="最大载重量(kg)">
                <el-input v-model="viewForm.max_weight" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库位位置X">
                <el-input v-model="viewForm.position_x" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="库位位置Y">
                <el-input v-model="viewForm.position_y" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库位位置Z">
                <el-input v-model="viewForm.position_z" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="允许产品混放">
                <el-input :value="viewForm.product_mixing === 'Y' ? '是' : '否'" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="允许批次混放">
                <el-input :value="viewForm.batch_mixing === 'Y' ? '是' : '否'" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否启用">
                <el-input :value="viewForm.enable_flag === 'Y' ? '是' : '否'" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否冻结">
                <el-input :value="viewForm.frozen_flag === 'Y' ? '是' : '否'" readonly placeholder="暂无数据" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="viewForm.remark" readonly type="textarea" placeholder="暂无数据" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
  </section>
</template>

<script>

import {listSas, saveSas, updateFrozen, findUnit, deleteAreaBatch} from "@/views/ck/js/setup"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";

export default {
  name: 'InventoryLocation',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      selectedRows: [],
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        location_id: undefined,
        area_code: undefined,
        area_name: undefined,
        position_x: undefined,
        position_y: undefined,
        position_z: undefined
      },
      // 表单参数
      form: {
        area_id: undefined,
        location_id: undefined,
        area_code: undefined,
        area_name: undefined,
        area: 1,
        max_weight: 1,
        position_x: 1,
        position_y: 1,
        position_z: 1,
        product_mixing: 'N',
        batch_mixing: 'N',
        enable_flag: 'Y',
        frozen_flag: 'N',
        remark: undefined,
        autoCode: false,
        create_by: '',
        update_by: '',
        unit_id: undefined
      },
      // 表单校验
      rules: {
        area_code: [
          { required: true, message: '库位编码不能为空', trigger: 'blur' }
        ],
        area_name: [
          { required: true, message: '库位名称不能为空', trigger: 'blur' }
        ]
      },
      frozenState:{
        id: '',
        type: 3,
        state: ''
      },
      //单位信息
      unitOptions: [],
      viewDialogVisible: false,
      viewForm: {}
    }
  },
  created() {
    // 从路由查询字符串中获取数据
    this.queryParams.location_id = this.$route.query.location_id;
    console.log('接收到的 location_id:', this.queryParams.location_id);
    this.getList()
    this.getUnitList();
  },
  methods: {
    // 表格多选
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    // 根据使用率设置样式
    getUsageStyle(row) {
      // 将字符串转为数值进行比较
      const usageRate = parseInt(row.used_capacity || 0);
      return {
        color: usageRate >= 80 ? '#ff4949' : '#67c23a',
        fontWeight: 'bold'
      };
    },
    // 获取列表数据
    getList() {
      this.loading = true
      listSas(this.queryParams).then(resp => {
        console.log("测试获取数据库位:"+resp.rows.length);
        this.tableData = resp.rows
        this.total = resp.total
        this.loading = false
      })
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        area_code: undefined,
        area_name: undefined,
        position_x: undefined,
        position_y: undefined,
        position_z: undefined
      }
      this.handleQuery()
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      if (this.unitOptions.length > 0) {
        this.form.unit_id = this.unitOptions[0].unit_id;
      }
      this.open = true
      this.title = '添加库位'
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      // 这里应该是API调用获取详情，模拟数据
      this.form = Object.assign({}, row)
      this.open = true
      this.title = '修改库位'
    },
    // 重置表单
    reset() {
      this.form = {
        area_id: undefined,
        area_code: undefined,
        area_name: undefined,
        area: 1,
        max_weight: 1,
        position_x: 1,
        position_y: 1,
        position_z: 1,
        product_mixing: 'N',
        batch_mixing: 'N',
        enable_flag: 'Y',
        frozen_flag: 'N',
        remark: undefined,
        autoCode: false,
        create_by: '',
        update_by: '',
        unit_id: undefined
      }
    },
    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在提交数据，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.form.location_id = this.queryParams.location_id
          // 修改逻辑
          if (this.form.area_id) {
            this.form.update_by = this.$store.getters.name; // 只更新修改人
            saveSas(this.form).then(resp => {
              loading.close();
              if (resp.flag) {
                this.open = false;
                this.getList();
                this.$message.success("修改成功");
              } else {
                this.$message.error(resp.msg || "修改失败");
              }
            }).catch(() => {
                loading.close();
                this.$message.error("修改操作失败");
            });
          }
          // 新增逻辑
          else {
            if (this.form.autoCode) {
              try {
                const response = await getAutoNumbersConsume(15);
                if (response.code === 200) {
                  this.form.area_code = response.msg;
                } else {
                  this.$message.error('获取库位编号失败: ' + response.msg);
                  loading.close();
                  return;
                }
              } catch (error) {
                this.$message.error('获取库位编号失败');
                loading.close();
                return;
              }
            }
            this.form.create_by = this.$store.getters.name;
            this.form.update_by = this.$store.getters.name;

            saveSas(this.form).then(saveResp => {
              loading.close();
              if (saveResp.flag) {
                this.open = false;
                this.getList();
                this.$message.success("新增成功");
              } else {
                this.$message.error(saveResp.msg || "新增失败");
              }
            }).catch(() => {
                loading.close();
                this.$message.error("新增操作失败");
            });
          }
        } else {
          return false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 删除按钮操作
    handleDelete(row) {
      const areaIds = row ? [row.area_id] : this.selectedRows.map(item => item.area_id);
      const areaNames = row ? row.area_name : this.selectedRows.map(item => item.area_name).join(', ');
      this.$confirm('是否确认删除库位名称为"' + areaNames + '"的数据项？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '正在删除，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          deleteAreaBatch(areaIds).then(response => {
            loading.close();
            if (response.code === 200) {
              this.getList();
              this.$message.success("删除成功");
            } else {
              this.$message.error(response.msg);
            }
          }).catch(() => {
            loading.close();
            this.$message.error("删除操作失败");
          });
        }).catch(() => {});
    },
    // 冻结状态改变
    handleFrozenChange(row) {
      const newStatus = row.frozen_flag;
      const oldStatus = newStatus === 'Y' ? 'N' : 'Y';
      const actionText = newStatus === 'Y' ? '冻结' : '解冻';

      this.$confirm(`确认要${actionText}库位"${row.area_name}"吗？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
            lock: true,
            text: `正在${actionText}，请稍候...`,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        // 确认操作，保持新状态
        this.frozenState.id = row.area_id
        this.frozenState.state = row.frozen_flag
        updateFrozen(this.frozenState).then(resp => {
          loading.close();
          if(resp.flag){
            this.$message.success(`${actionText}成功`);
          }else{
            this.$message.error(`${actionText}失败`);
            row.frozen_flag = oldStatus;
          }
        }).catch(() => {
          loading.close();
          row.frozen_flag = oldStatus;
          this.$message.error(`${actionText}失败`);
        });

      }).catch(() => {
        // 取消操作，恢复原状态
        row.frozen_flag = oldStatus;
        this.$message.info('已取消操作');
      });
    },
    // 标签打印
    handlePrint(row) {
      // 打印标签
      console.log('打印标签', row)
    },
    handleAutoCodeChange(val) {
      if (val) {
        getAutoNumbers(15).then(resp => {
          this.form.area_code = resp.msg;
        });
      } else {
        this.form.area_code = '';
      }
    },
    //获取单位信息
    getUnitList() {
      findUnit().then(resp => {
        this.unitOptions = resp.dataList;
        if (!this.form.unit_id && this.unitOptions.length > 0) {
          this.form.unit_id = this.unitOptions[0].unit_id;
        }
      });
    },
    handleView(row) {
      this.viewForm = { ...row };
      this.viewDialogVisible = true;
    }
  }
}
</script>

<style scoped>
.app-main {
  padding: 10px;
}
.app-container {
  padding: 5px;
}
.mb8 {
  margin-bottom: 8px;
}
.top-right-btn {
  float: right;
}
</style>
